/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

function bind(self, method, var_args) {
  var args = Array.prototype.slice.call(arguments, 2);

  return function(var_args) {
    method.apply(self,
        args.concat(Array.prototype.slice.call(arguments)));
  };
}

function Util() {
}

Util.createRequest = function() {
  var xhr;

  try {
    xhr = framework.google.betaXmlHttpRequest();
  } catch (e) {
    xhr = new XMLHttpRequest();
  }

  return xhr;
};

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
};

Util.openBrowser = function(url) {
  framework.openUrl(url);
};

// TODO: this function is NOT i18-compliant.
Util.trimDecimalDigitsIfGe1000 = function(original) {
  var n;

  n = original;

  if (n.length > 7) {
    // n,nnn.nn
    var lastChar = n.substring(n.length - 1, n.length);
    if (lastChar != 'M' && lastChar != 'B') {
      if (n.substring(n.length - 3 ,n.length - 2) == '.') {
        n = n.substring(0, n.length - 3);
      }
    }
  }

  return n;
};

Util.substitutePH = function(s, ph, value) {
  return s.replace(ph, value);
};

Util.retrieveImage = function(img, url) {
  var req = Util.createRequest();

  req.open('GET', url, true);

  req.onreadystatechange = function(img, req) {
    return function() {
      Util.onImageData(img, req);
    };
  }(img, req);

  req.send();
};

Util.onImageData = function(img, req) {
  if (req.readyState != 4) {
    return;
  }

  if (req.status != 200) {
    return;
  }

  img.src = req.responseStream;
};

Util.onlineChecker = null;

Util.isOnline = function() {
  if (!Util.onlineChecker) {
    Util.onlineChecker = new OnlineChecker();
  }

  return Util.onlineChecker.isOnline();
};
